import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { useEffect, useRef, useState } from 'react';
import { Button, message, Modal } from 'antd';
import OrderListTable from '../OrderListTable';
import AfterSalesInfo from '../AfterSalesInfo';
import GoodsListTable from '../GoodsListTable';
import { LeftOutlined } from '@ant-design/icons';
import { queryExpressList, manualCreate, noHeadClaim } from '../../services';
import { find } from 'lodash';

//格式化商品列表
const formatGoodsList = (item) => {
	if (item.goodsList) {
		item.goodsList.map(v => {
			v.applyCount = v.goodsNum;
		})
		return item.goodsList;
	}
	return [];
}

/** 新建售后单 */
function CreateAfterSales(props) {
	const { item, handleOk, handleCancel } = props;
	const { scene } = item;
	const [isOk, setIsOk] = useState(false);
	const [loading, setLoading] = useState(false);
	const [open, setOpen] = useState(false);
	const [orderInfo, setOrderInfo] = useState({ goodsList: formatGoodsList(item) });
	const infoRef = useRef(null);
	const [goodsList, setGoodsList] = useState(formatGoodsList(item));

	//下拉快递列表
	const [expressList, setExpressList] = useState([]);

	//新建售后单类型，正常还是无信息
	const [createType, setCreateType] = useState('normal')

	useEffect(() => {
		getExpressList();
		setOpen(true);
	}, [])

	//获取快递列表
	const getExpressList = async () => {
		const { success, data } = await queryExpressList();
		if (success) {
			setExpressList(data);
		}
	};

	const onOk = () => {
		const afterInfo = infoRef.current.getFieldsValue();
		//无信息件认领需要判断商品是否一致
		let totalNum = goodsList.reduce((pre, next) => { return pre + Number(next.applyCount || 0) }, 0);
		if (totalNum == 0 && goodsList.length > 0) {
			message.info('商品申请数量不能为空')
			return;
		}
		if (scene == 'unInfoClaim') {
			handleClaim(afterInfo);
		} else {
			handleCreate(afterInfo);
		}
	}

	//检测商品是否一致
	const handleCheckGoods = () => {
		if (goodsList.length != orderInfo.goodsList.length) {
			return false;
		}
		for (let i in goodsList) {
			for (let k in orderInfo.goodsList) {
				if (orderInfo.goodsList[k].ecSkuId != goodsList[i].ecSkuId) {
					return false;
				}
			}
		}
		return true;
	}

	//参数设置orderId
	const handleClaim = (val) => {
		if (!orderInfo.orderId) {
			message.info('请先绑定订单');
			return;
		}
		const isSameGoods = handleCheckGoods();
		const desc = isSameGoods ? '订单绑定后不允许进行修改' : '售后商品与订单商品不符，请确认是否绑定？订单绑定后按照申请售后的商品处理，不允许二次修改';
		Modal.confirm({
			title: '提示信息',
			content: desc,
			onOk() {
				handleCreate(val, true);
			}
		})
	}

	//创建售后单
	const handleCreate = async (afterInfo, isClaim) => {
		setLoading(true);
	
		const params = {
			...afterInfo,
			...orderInfo,
		}
		//无信息件认领需要售后单id
		if (isClaim) {
			params.afterSaleId = item.id;
			goodsList.map(v => {
				v.createTime = undefined;
				v.goodsNum = Number(v.applyCount);
				v.refundAmount = v.goodsPrice * v.applyCount;
				delete v.applyCount;
				const obj = find(orderInfo.goodsList, ['ecSkuId', v.ecSkuId]);
				if(obj) {
					v.orderGoodsId = obj.id;
				}
				Object.keys(v).map(k => {
					if (v[k] == null) {
						delete v[k];
					}
				})
			})
			params.goodsList = goodsList;
		} else {
			goodsList.map(v => {
				v.createTime = undefined;
				v.goodsNum = Number(v.applyCount);
				v.refundAmount = v.goodsPrice * v.applyCount;
				delete v.applyCount;
				Object.keys(v).map(k => {
					if (v[k] == null) {
						delete v[k];
					}
				})
			})
			params.goodsList = goodsList;
		}
		if (params.refundLogisticsId) {
			const obj = find(expressList, ['id', params.refundLogisticsId]);
			params.refundLogisticsCompany = obj.name;
		}
		const saveApi = scene == 'unInfoClaim' ? noHeadClaim : manualCreate;
		const { success } = await saveApi(params);
		if (success) {
			let timer = setTimeout(() => {
				setIsOk(true);
				setOpen(false);
				message.success('创建成功');
				setLoading(false);
				clearTimeout(timer);
				timer = null;
			}, 3000)
		} else {
			setLoading(false);
		}
	}

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		if (isOk) {
			handleOk(2);
		} else {
			handleCancel();
		}
	}

	//订单信息
	const OrderListTableProps = {
		scene,
		createType,
		setLoading,
		setGoodsList,
		setOrderInfo,
		changeCreateType() {
			setCreateType('noMessage');
			setOrderInfo({});
		}
	}

	//售后详情
	const AfterSalesInfoProps = {
		item,
		expressList,
		elRef: infoRef,
		createType
	}

	//售后商品详情
	const GoodsListTableProps = {
		scene,
		createType,
		goodsList,
		handleSaveData(data) {
			setGoodsList(data);
		}
	}

	const footer = (
		<div>
			<Button onClick={onCancel}>取消</Button>
			<Button onClick={onOk} type="primary">确定创建售后单</Button>
		</div>
	)

	const title = scene == 'unInfoClaim' ? '无信息件认领' : '新建售后单';

	return (
		<CommonModal title={title} footer={footer} afterClose={afterClose} open={open} width="1200px" onOk={onOk} onCancel={onCancel}>
			{createType == 'normal' && <OrderListTable {...OrderListTableProps} />}
			{createType == 'noMessage' && <div onClick={() => setCreateType('normal')} style={{ cursor: 'pointer' }}>
				<LeftOutlined style={{ color: '#0068FF', marginRight: '4px' }} />
				返回正常创建售后单
			</div>}
			<AfterSalesInfo {...AfterSalesInfoProps} />
			<GoodsListTable {...GoodsListTableProps} />
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default CreateAfterSales;
